import { useState, useEffect } from 'react'
import { useTheme } from '@/hooks/useTheme'
import AppIcon from '@/components/AppIcon'
import DateTimeDisplay from '@/components/DateTimeDisplay'

import ThemeToggle from '@/components/ThemeToggle'
import SearchBar from '@/components/SearchBar'
import BackgroundSettings from '@/components/BackgroundSettings'
import Calendar from '@/components/Calendar'
import WebsiteForm from '@/components/WebsiteForm'
import {
  BackgroundStorage,
  WebsiteStorage,
  fetchBingWallpapers,
} from '@/lib/utils'
import { toast } from 'sonner'

export default function Home() {
  const { theme } = useTheme()
  const [backgroundImage, setBackgroundImage] = useState<string | null>(null)
  const [websites, setWebsites] = useState<
    Array<{ id: number; name: string; icon: string; url: string }>
  >([])
  const [showBackgroundSettings, setShowBackgroundSettings] = useState(false)
  const [showWebsiteForm, setShowWebsiteForm] = useState(false)
  const [editingWebsite, setEditingWebsite] = useState<
    { id: number; name: string; icon: string; url: string } | undefined
  >()
  const [showCalendar, setShowCalendar] = useState(false)
  const [bingWallpapers, setBingWallpapers] = useState<string[]>([])
  const [currentWallpaperIndex, setCurrentWallpaperIndex] = useState(0)
  const [wallpaperInterval, setWallpaperInterval] = useState<number | null>(
    null
  )

  // 加载保存的背景图片和网站数据
  useEffect(() => {
    const savedBackground = BackgroundStorage.get()
    if (savedBackground) {
      setBackgroundImage(savedBackground)
    }

    // 加载网站数据
    const loadWebsites = () => {
      const savedWebsites = WebsiteStorage.get()
      setWebsites(savedWebsites)
    }

    loadWebsites()

    // 获取Bing壁纸并设置自动切换
    const initBingWallpapers = async () => {
      try {
        const wallpapers = await fetchBingWallpapers()

        setBingWallpapers(wallpapers)

        // 如果有壁纸且没有自定义背景，设置第一张为背景
        if (wallpapers.length > 0 && !savedBackground) {
          setBackgroundImage(wallpapers[0])
          
          // 设置定时器，每1秒切换一次壁纸
          const interval = setInterval(() => {

            setCurrentWallpaperIndex((prevIndex) => {
              const newIndex = (prevIndex + 1) % wallpapers.length
              setBackgroundImage(wallpapers[newIndex])
              return newIndex
            })
          }, 1000)

          setWallpaperInterval(interval)
        }

        // 检查是否使用了默认壁纸（API请求失败）
        if (
          wallpapers.length > 0 &&
          wallpapers[0].includes('coze.cn/api/coze_space/gen_image')
        ) {
          toast.info('使用默认壁纸，Bing壁纸服务暂时不可用')
        }
      } catch (error) {
        console.error('初始化壁纸失败:', error)
        toast.error('壁纸加载失败，请检查网络连接')
      }
    }

    initBingWallpapers()
  }, [])

  // 当自定义背景更改或组件卸载时清除定时器
  useEffect(() => {
    return () => {
      if (wallpaperInterval) {
        clearInterval(wallpaperInterval)
      }
    }
  }, [wallpaperInterval])

  // 当自定义背景被设置时，停止自动切换
  useEffect(() => {
    if (backgroundImage && wallpaperInterval) {
      clearInterval(wallpaperInterval)
      setWallpaperInterval(null)
    } else if (
      !backgroundImage &&
      bingWallpapers.length > 0 &&
      !wallpaperInterval
    ) {
      // 如果没有自定义背景且有Bing壁纸，但没有定时器，则重新启动定时器
      const interval = setInterval(() => {
        setCurrentWallpaperIndex((prevIndex) => {
          const newIndex = (prevIndex + 1) % bingWallpapers.length
          setBackgroundImage(bingWallpapers[newIndex])
          return newIndex
        })
      }, 1000)
      setWallpaperInterval(interval)
    }
  }, [backgroundImage, bingWallpapers])

  // 应用背景图片
  const applyBackgroundImage = (imageData: string | null) => {
    setBackgroundImage(imageData)
    if (imageData) {
      BackgroundStorage.set(imageData)
    } else {
      BackgroundStorage.remove()
    }
  }

  return (
    <div
      className="min-h-screen flex flex-col items-center justify-center p-4 relative"
      style={{
        backgroundImage: backgroundImage
          ? `url(${backgroundImage})`
          : theme === 'dark'
          ? 'linear-gradient(to bottom, #1a1a1a 0%, #0a0a0a 100%)'
          : 'linear-gradient(to bottom, #f5f5f7 0%, #ffffff 100%)',
        backgroundSize: 'cover',
        backgroundPosition: 'center',
        backgroundAttachment: 'fixed',
      }}
    >
      <ThemeToggle />

      <DateTimeDisplay />
      <SearchBar />

      {/* 添加网站按钮 */}
      <button
        onClick={() => {
          setEditingWebsite(undefined)
          setShowWebsiteForm(true)
        }}
        className="fixed bottom-8 right-8 p-3 rounded-full bg-blue-500 text-white shadow-lg hover:bg-blue-600 transition-all duration-200 hover:shadow-xl"
        aria-label="添加常用网站"
      >
        <i className="fa-solid fa-plus"></i>
      </button>

      {/* 背景设置按钮 */}
      <button
        onClick={() => setShowBackgroundSettings(true)}
        className="absolute top-4 left-16 p-2 rounded-full bg-white/80 dark:bg-gray-800/80 shadow-sm border border-gray-100 dark:border-gray-700 text-gray-700 dark:text-gray-300 transition-all duration-200 hover:shadow-md"
        aria-label="背景设置"
      >
        <i className="fa-solid fa-image"></i>
      </button>

      {/* 背景设置面板 */}
      <BackgroundSettings
        isOpen={showBackgroundSettings}
        onClose={() => setShowBackgroundSettings(false)}
        onBackgroundChange={applyBackgroundImage}
      />

      {/* 网站表单模态框 */}
      <WebsiteForm
        isOpen={showWebsiteForm}
        onClose={() => setShowWebsiteForm(false)}
        onSave={(websiteData) => {

          if (editingWebsite) {
            // 更新现有网站
            WebsiteStorage.update({ ...editingWebsite, ...websiteData })
            setWebsites(
              websites.map((w) =>
                w.id === editingWebsite.id
                  ? { ...editingWebsite, ...websiteData }
                  : w
              )
            )
            toast.success(`已更新网站: ${websiteData.name}`)
          } else {
            // 添加新网站
            WebsiteStorage.add(websiteData)
            setWebsites([
              ...websites,
              {
                ...websiteData,
                id:
                  websites.length > 0
                    ? Math.max(...websites.map((w) => w.id)) + 1
                    : 1,
              },
            ])
            toast.success(`已添加新网站: ${websiteData.name}`)
          }
          setShowWebsiteForm(false)
          setEditingWebsite(undefined)
        }}
        initialData={editingWebsite}
      />

      {/* 常用网站图标网格 */}
      <div className="grid grid-cols-4 sm:grid-cols-6 md:grid-cols-8 gap-6 sm:gap-8 max-w-4xl w-full">
        {websites.map((website) => (
          <AppIcon
            key={website.id}
            name={website.name}
            icon={website.icon}
            url={website.url}
            isEditable={true}
            onEdit={() => {
              setEditingWebsite(website)
              setShowWebsiteForm(true)
            }}
            onDelete={() => {
              if (window.confirm(`确定要删除 "${website.name}" 吗?`)) {
                WebsiteStorage.remove(website.id)
                setWebsites(websites.filter((w) => w.id !== website.id))
                toast.success(`已删除网站: ${website.name}`)
              }
            }}
          />
        ))}

        {/* 添加网站按钮（网格中的最后一个） */}
        <button
          onClick={() => {
            setEditingWebsite(undefined)
            setShowWebsiteForm(true)
          }}
          className="flex flex-col items-center justify-center w-full h-24 border-2 border-dashed border-gray-300 dark:border-gray-600 rounded-xl bg-white/50 dark:bg-gray-800/50 hover:bg-white/80 dark:hover:bg-gray-800/80 transition-all duration-200 cursor-pointer group"
        >
          <div className="w-12 h-12 rounded-full bg-gray-100 dark:bg-gray-700 flex items-center justify-center group-hover:bg-blue-100 dark:group-hover:bg-blue-900 transition-colors">
            <i className="fa-solid fa-plus text-gray-400 dark:text-gray-500 group-hover:text-blue-500 dark:group-hover:text-blue-400"></i>
          </div>
          <span className="text-xs text-gray-500 dark:text-gray-400 mt-2">
            添加网站
          </span>
        </button>

        {/* 日历按钮 */}
        <button
          onClick={() => setShowCalendar(true)}
          className="absolute top-4 left-28 p-2 rounded-full bg-white/80 dark:bg-gray-800/80 shadow-sm border border-gray-100 dark:border-gray-700 text-gray-700 dark:text-gray-300 transition-all duration-200 hover:shadow-md"
          aria-label="日历"
        >
          <i className="fa-solid fa-calendar"></i>
        </button>
      </div>

      {/* 日历组件 */}
      <Calendar isOpen={showCalendar} onClose={() => setShowCalendar(false)} />

      <div className="absolute bottom-6 text-xs text-gray-400 dark:text-gray-500">
        <p>© 2025 kk起始页</p>
      </div>
    </div>
  )
}
